//
//  ECOrderListViewController.m
//  ECERP.CRM
//
//  Created by 刘思麟 on 2018/10/24.
//  Copyright © 2018年 Mac. All rights reserved.
//

#import "ECMemberListViewController.h"
#import "ECMemberListTableViewCell.h"
#import "ECMemberLIstModel.h"
#import "ECMemberAddViewController.h"
#import "ECMemberSideslipView.h"

@interface ECMemberTableView:UITableView

@end


@interface ECMemberListViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>

@property (nonatomic,strong) ECMemberTableView * tableView;

@property (nonatomic,strong) NSMutableArray<ECMemberLIstModel*> * dataArr;

@property (nonatomic,assign) NSInteger cuPage;

@property (nonatomic,strong) UIView * searchToolView;

@property (nonatomic,strong) UISearchBar * searchBar;

@property (nonatomic,strong) UIButton * searchSelectBT;

@property (nonatomic,strong) UILabel * sumLB;

@property (nonatomic,strong) UIWindow * effectWindow;

@property (nonatomic,strong) ECMemberSideslipView * sideslipView;

@end


@implementation ECMemberTableView

- (void)layoutSubviews {
    [super layoutSubviews];
    for (UIView * subView in self.subviews) {
        if ([subView isKindOfClass:NSClassFromString(@"UISwipeActionPullView")]) {
            for (int index =0 ;index<subView.subviews.count;index++) {
                UIView * childView = subView.subviews[index];
                for (UIView *scV in childView.subviews) {
                    if ([scV isKindOfClass:NSClassFromString(@"UIButtonLabel")]) {
                        if (index == 0) {
                            ((UILabel*)scV).textColor = ECCOLOR(0x41d95a);
                        }
                        ((UILabel*)scV).font = ECFONT(16 * PX_RELATIVE375);
                    }
                }
            }
        }
    }
}

@end

@implementation ECMemberListViewController

- (void)viewDidLoad {
    self.cuPage = 1;
    self.navigationItem.title = @"客户";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"add_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(doAdd)];
    [super viewDidLoad];
    [self requestData:self.cuPage];
    // Do any additional setup after loading the view.
}

- (void)loadSubView {
    __weak typeof(self) weakSelf = self;
    [self.view addSubview:self.searchToolView];
    [self.searchToolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(54);
    }];
    [self.searchToolView addSubview:self.searchSelectBT];
    [self.searchSelectBT mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(weakSelf.searchToolView);
        make.right.mas_equalTo(weakSelf.searchToolView).mas_offset(-10);
        make.height.with.mas_equalTo(24);
    }];
    
    self.searchBar.layer.cornerRadius = 16;
    self.searchBar.clipsToBounds = YES;
    self.searchBar.layer.borderWidth = 1;
    self.searchBar.layer.borderColor = ECCOLOR(0xcccccc).CGColor;
    [self.searchToolView addSubview:self.searchBar];
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(weakSelf.searchToolView).mas_offset(12*PX_RELATIVE375);
        make.centerY.mas_equalTo(weakSelf.searchToolView);
        make.height.mas_equalTo(32);
        make.right.mas_equalTo(weakSelf.searchSelectBT.mas_left).mas_offset(-5);
    }];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(weakSelf.searchToolView.mas_bottom);
    }];
}

- (void)requestData:(NSInteger)page {
    NSMutableDictionary * paraDic = @{@"page":@(page),@"limit":@(20),}.mutableCopy;
    [GLHTTPTool getWithURL:Api_MemberList(@"o") params:paraDic success:^(id json) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if ([json[@"code"] integerValue] == 0) {
            NSArray * daraAr = [NSArray modelArrayWithClass:[ECMemberLIstModel class] json:json[@"data"]];
            if (self.cuPage <= 1) {
                self.dataArr = daraAr;
            }else {
                [self.dataArr addObjectsFromArray:daraAr];
                [self.tableView reloadData];
            }
            if (daraAr.count >= 20) {
                self.cuPage = page + 1;
            }else {
                self.cuPage = page;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }else{
            self.cuPage = page;
            [MBProgressHUD showMessage:json[@"msg"] toView:self.view];
        }
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        self.cuPage = page;
    }];
}

- (void)setDataArr:(NSMutableArray *)dataArr {
    _dataArr = dataArr;
    if (_dataArr && _dataArr.count > 0) {
        [self.tableView reloadData];
        self.dataState = ECBaseDataStateData;
    }else {
        self.dataState = ECBaseDataStateNOData;
    }
}

- (void)doAdd {
    ECMemberAddViewController * vc = [ECMemberAddViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)doFilter:(UIButton*)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self showFilter];
    }
}

- (void)showFilter {
    WS(weakSelf, self);
    [self.effectWindow makeKeyAndVisible];
    self.effectWindow.hidden = NO;
    [UIView animateWithDuration:0.25 animations:^{
        weakSelf.effectWindow.backgroundColor = [weakSelf.effectWindow.backgroundColor colorWithAlphaComponent:0.62];
        weakSelf.sideslipView.x = 51 * PX_RELATIVE375;
    } completion:nil];
}

#pragma mark -UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 27;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return @" ";
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    __weak typeof(view) weakView = view;
    view.backgroundColor = ECCOLOR(0xf5f5f5);
//    [view removeAllSubviews];
    if (self.sumLB.superview != view) {
        [view addSubview:self.sumLB];
    }
    [self.sumLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(weakView);
        make.left.mas_equalTo(weakView).mas_offset(18*PX_RELATIVE375);
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100 * PX_RELATIVE375;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ECMemberLIstModel * model = self.dataArr[indexPath.row];
    ECMemberListTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.titleLB.text = model.customerName;
    cell.stateLB.text = model.enabled == 1 ? @"正常":@"禁用";
    cell.stateLB.textColor = model.enabled == 1 ? ECCOLOR(0x41d95a):ECCOLOR(0xff3333);
    cell.dateLB.text = model.customerLastTradeTime;
    cell.codeLB.text = [NSString stringWithFormat:@"客户编码：%@",model.customerCode];
    cell.sourceLB.text = [NSString stringWithFormat:@"客户来源：易升鲜%@",model.customerSource];
    return cell;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleNone;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewRowAction * action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"禁用" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
    }];
    action1.backgroundColor = ECCOLOR(0xff3333);
    
    UITableViewRowAction * action2 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"重置" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
    }];
    action2.backgroundColor = ECCOLOR(0x41d95a);
    
    UITableViewRowAction * action3 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"编辑" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
    }];
    action3.backgroundColor = ECCOLOR(0xd8ffd8);
    return @[action1,action2,action3];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.cellSelectedBlock) {
        ECMemberLIstModel * model = self.dataArr[indexPath.row];
        self.cellSelectedBlock(model);
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark LazyLoad

- (ECMemberTableView *)tableView {
    if (!_tableView) {
        __weak typeof(self) weakSelf = self;
        _tableView = [[ECMemberTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.00000001)];
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.00000001)];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.sectionHeaderHeight = 27 * PX_RELATIVE375;
        _tableView.sectionFooterHeight = 0.00001 * PX_RELATIVE375;
        [_tableView registerClass:[ECMemberListTableViewCell class] forCellReuseIdentifier:@"cell"];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf requestData:1];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [weakSelf requestData:self.cuPage];
        }];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (UIView *)searchToolView {
    if (!_searchToolView) {
        _searchToolView = [UIView new];
    }
    return _searchToolView;
}

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [UISearchBar new];
        [_searchBar setImage:[UIImage imageNamed:@"search_member"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
        _searchBar.placeholder = @"客户名称/编号/联系人/手机号码";
        [_searchBar setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]]];
        [_searchBar setPositionAdjustment:UIOffsetMake(-6, 0) forSearchBarIcon:UISearchBarIconSearch];
        for (UIView * v in _searchBar.subviews.firstObject.subviews) {
            if ([v isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
                UITextField * tf = (UITextField*)v;
                tf.font = ECFONT(14);
            }
        }
    }
    return _searchBar;
}

- (UIButton *)searchSelectBT {
    if (!_searchSelectBT) {
        _searchSelectBT = [UIButton buttonWithType:UIButtonTypeCustom];
        [_searchSelectBT setBackgroundImage:[UIImage imageNamed:@"select_member"] forState:UIControlStateNormal];
        [_searchSelectBT setBackgroundImage:[UIImage imageNamed:@"select_member_on"] forState:UIControlStateSelected];
        [_searchSelectBT addTarget:self action:@selector(doFilter:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _searchSelectBT;
}

- (UILabel *)sumLB {
    if (_sumLB) {
        _sumLB = [UILabel new];
        _sumLB.textColor = ECCOLOR(0xb5b5b5);
        _sumLB.font = ECFONT(13);
    }
    return _sumLB;
}

- (UIWindow *)effectWindow {
    if (!_effectWindow) {
        WS(weakSelf, self);
        _effectWindow = [UIWindow new];
        _effectWindow.backgroundColor = [ECCOLOR(0x010101) colorWithAlphaComponent:0.62];
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            [UIView animateWithDuration:0.25 animations:^{
                weakSelf.sideslipView.x = ECSCREEN_WIDTH;
                weakSelf.effectWindow.backgroundColor = [weakSelf.effectWindow.backgroundColor colorWithAlphaComponent:0.0001];
            } completion:^(BOOL finished) {
                weakSelf.effectWindow.hidden = YES;
                [weakSelf.effectWindow resignKeyWindow];
                [weakSelf.searchSelectBT setSelected:NO];
            }];
        }];
        tap.delegate = self;
        [_effectWindow addGestureRecognizer:tap];
        self.sideslipView = [ECMemberSideslipView new];
        [_effectWindow addSubview:self.sideslipView];
        self.sideslipView.frame = CGRectMake(375 * PX_RELATIVE375, 0, 324 * PX_RELATIVE375, ECSCREEN_HEIGHT);
    }
    return _effectWindow;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if (CGRectContainsPoint(self.sideslipView.bounds, [touch locationInView:self.sideslipView])) {
        return NO;
    }
    return YES;
}

@end
